package com.incar.chuxing.activity.driving;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;

import com.baidu.ocr.ui.camera.CameraThreadPool;
import com.baidu.ocr.ui.camera.ICameraControl;
import com.baidu.ocr.ui.camera.MaskView;
import com.incar.chuxing.R;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.UploadImageBaidu;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.bos.UploadPicUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ReturnCarCameraActivity extends BaseActivity {

    private Context mContext = this;
    private AnimationSet animationSet;

    @BindView(R.id.cameraView)
    com.baidu.ocr.ui.camera.CameraView cameraView;
    @BindView(R.id.take_photo_button)
    ImageView takePhotoButton;
    @BindView(R.id.light_button)
    ImageView lightButton;
    @BindView(R.id.back_button)
    ImageView backButton;
    @BindView(R.id.iv_preview)
    ImageView ivPreview;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    break;
                case 2:
                    //成功压缩
                    //上传图片
                    Logger.d("returnCar", "压缩成功" + compressFile.getName());
                    uploadImage(compressFile);
                    break;
                case 3:
                    //压缩失败
                    Logger.d("returnCar", "压缩失败" + compressFile.getName());
                    break;
                case 4: //上传成功
                    Logger.d("returnCar", "上传成功" + compressFile.getName());
                    SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PIC_NAME, SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) + "," + compressFile.getName());
                    Logger.d("returnCar", "上传成功总共" + SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME));
                    break;
                case 5:
                    //上传失败
                    Logger.d("returnCar", "上传失败" + compressFile.getName());
                    break;
                case 6:
                    //上传取消
                    Logger.d("returnCar", "上传取消" + compressFile.getName());
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private String key;
    private File compressFile;
    private int i = 0;
    private String orderId;
    private List<Map<String, Object>> datas;
    private File outputFile;

    @Override
    public int getLayoutId() {
        return R.layout.activity_return_car_camera;
    }

    @Override
    public void initView() {

        int maskType = MaskView.MASK_TYPE_NONE;
        cameraView.setMaskType(maskType, this);

        orderId = getIntent().getStringExtra("orderId");
        animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 0.35f, 1f, 0.35f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(600);

        AlphaAnimation alpha = new AlphaAnimation(1f, 0);
        alpha.setDuration(500);
        alpha.setStartOffset(1500);
        animationSet.addAnimation(alpha);
        animationSet.addAnimation(scaleAnimation);
        ivPreview.setAlpha(0.9f);
        alpha.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                ivPreview.setVisibility(View.GONE);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        takePhotoButton.setOnClickListener(v -> {
            checkperssionAndCamera();
        });
    }

    private void takephoto() {
        takePhotoButton.setClickable(false);
        outputFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "returncar.jpg");
        cameraView.takePicture(outputFile, takePictureCallback);
    }

    public void checkperssionAndCamera() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), 0);
            } else {
                takephoto();
            }
        } else {
            takephoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    }

    private com.baidu.ocr.ui.camera.CameraView.OnTakePictureCallback takePictureCallback = new com.baidu.ocr.ui.camera.CameraView.OnTakePictureCallback() {
        @Override
        public void onPictureTaken(final Bitmap bitmap) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    ivPreview.setImageBitmap(bitmap);
                    ivPreview.setVisibility(View.VISIBLE);
                    ivPreview.startAnimation(animationSet);
                }
            });
            Luban.with(mContext)
                    .load(outputFile)  //传入要压缩的图片
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            Message message = new Message();
                            message.arg1 = 2;
                            Logger.d("returnCarRrename1", file.getAbsolutePath());
                            File fileDir = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "returncar");
                            if (!fileDir.exists()) {
                                fileDir.mkdirs();
                            }
                            SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PIC_DIC, fileDir.getAbsolutePath());
                            compressFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "returncar" + File.separator + orderId + "-" + SDCardUtils.createReturnCarFileName(((MyApplication) getApplication()).getUid()) + ".jpg");
                            file.renameTo(compressFile);
                            Logger.d("returnCarRename2", compressFile.getAbsolutePath());
                            takePhotoButton.setClickable(true);
                            if (++i == 6) {
                                startActivity(new Intent(mContext, ReturnCarActivity.class));
                                AppManager.getAppManager().finishActivity(ReturnCarCameraActivity.this);
                            }
                            handler.sendMessage(message);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Message message = new Message();
                            message.arg1 = 3;
                            handler.sendMessage(message);
                        }
                    }).launch();    //启动压缩
        }
    };

    private void uploadImage(final File picFile) {
        Logger.d("returnCar", "开始上传" + compressFile.getName());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        key = getFileNameNoEx(picFile);
                        Logger.d("returnCar", key + "");
                        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                                response.body().getAttachment().getStsToken(),
                                response.body().getAttachment().getBucketName(),
                                key, new UploadPicUtil.OnFinishListener() {
                                    @Override
                                    public void onSuccess() {
                                        Message message = new Message();
                                        message.arg1 = 4;
                                        Bundle b = new Bundle();
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onFailure(String failReason) {
                                        Message message = new Message();
                                        message.arg1 = 5;
                                        Bundle b = new Bundle();
                                        b.putString("failReason", failReason);
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }
                                });

                    } else {
                    }
                } else {
                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {

            }
        });
    }

    /*
     * Java文件操作 获取不带扩展名的文件名
     */
    public String getFileNameNoEx(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                int index = filename.indexOf("-");
                return filename.substring(index + 1, dot);
            }
        }
        return filename;
    }

    @OnClick({R.id.back_button, R.id.light_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_button:
                onBackPressed();
                break;
            case R.id.light_button:
                if (cameraView.getCameraControl().getFlashMode() == ICameraControl.FLASH_MODE_OFF) {
                    cameraView.getCameraControl().setFlashMode(ICameraControl.FLASH_MODE_TORCH);
                } else {
                    cameraView.getCameraControl().setFlashMode(ICameraControl.FLASH_MODE_OFF);
                }
                updateFlashMode();
                break;
        }
    }

    private void updateFlashMode() {
        int flashMode = cameraView.getCameraControl().getFlashMode();
        if (flashMode == ICameraControl.FLASH_MODE_TORCH) {
            lightButton.setImageResource(com.baidu.ocr.ui.R.drawable.bd_ocr_light_on);
        } else {
            lightButton.setImageResource(com.baidu.ocr.ui.R.drawable.bd_ocr_light_off);
        }
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(mContext, ReturnCarActivity.class));
        AppManager.getAppManager().finishActivity(ReturnCarCameraActivity.this);
    }

    @Override
    protected void onResume() {
        cameraView.start();
        datas = new ArrayList<>();
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC) != null) {
            File fileDir = new File(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC));
            File[] files = fileDir.listFiles();
            if (null != files) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                        Logger.d("returnCarrename3", files[i].getAbsolutePath());
                        Map<String, Object> map = new HashMap<>();
                        map.put("path", files[i].getAbsolutePath());
                        datas.add(map);
                    }
                }
            }
            i = datas.size();
        } else {
            i = 0;
            datas = null;
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        cameraView.stop();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (animationSet != null) {
            animationSet.reset();
        }
        super.onDestroy();
        CameraThreadPool.cancelAutoFocusTimer();
    }
}
